package apis

import (
	"fmt"
	ext "go-admin/config"
	"gorm.io/gorm/clause"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"

	"github.com/tidwall/gjson"
	"go-admin/app/admin/models"
	"go-admin/app/admin/service"
	"go-admin/app/admin/service/dto"
	"go-admin/common/actions"
)

type SysMemberGoods struct {
	api.Api
}

// SyncMemberGoodsFromDm2c 从dm2c同步会员商品数据
// @Summary 从dm2c同步会员商品数据
// @Description 从dm2c同步会员商品数据
// @Tags 线下会员商品表
// @Param id query int false "主键Id"
// @Param category query string false "分类"
// @Param goodsType query string false "商品大类"
// @Param goodsModel query string false "商品型号"
// @Param goodsCode query string false "商品编码"
// @Param goodsName query string false "商品名称"
// @Param goodsSpeci query string false "商品规格"
// @Param remark query string false "备注"
// @Param status query string false "业务状态"
// @Param isDeleted query string false "删除状态"
// @Param createTime query time.Time false "创建时间"
// @Param createAccount query string false "创建人"
// @Param createOrg query string false "创建部门"
// @Param updateAccount query string false "修改人"
// @Param updateTime query time.Time false "修改时间"
// @Success 200
// @Router /api/v1/sync-member-goods [get]
// @Security Bearer
func (e SysMemberGoods) SyncMemberGoodsFromDm2c(c *gin.Context) {

	apiUrl := ext.ExtConfig.Dm2c.Api
	appCode := ext.ExtConfig.Dm2c.AppCode
	pageNum := 1
	pageSize := 200
	for {
		params := &dto.Dm2cParams{AppCode: appCode, PageNum: pageNum, PageSize: pageSize}
		startTime := time.Now()
		resp, err := http.Get(apiUrl + "?appCode=" + params.AppCode + "&pageNum=" + strconv.Itoa(params.PageNum) + "&pageSize=" + strconv.Itoa(params.PageSize))
		costTime := time.Since(startTime)
		fmt.Printf("调用dm2c平台接口耗时: %v 秒 \n", costTime.Seconds())
		if err != nil {
			e.Error(500, err, fmt.Sprintf("调用dm2c平台接口异常: %s", err.Error()))
			break
		}

		body, readBodyErr := ioutil.ReadAll(resp.Body)
		if readBodyErr != nil {
			e.Error(500, readBodyErr, fmt.Sprintf("读取数据异常: %s", readBodyErr.Error()))
			break
		}

		// defer关键字 等同于 runtime.deferproc() defer用于资源的释放,会在函数返回之前进行调用
		// defer resp.Body.Close()
		closeBodyErr := resp.Body.Close()
		if closeBodyErr != nil {
			e.Error(500, closeBodyErr, fmt.Sprintf("关闭流数据异常: %s", closeBodyErr.Error()))
			break
		}

		resultData := gjson.Get(string(body), "data")
		resultRows := resultData.Get("rows")
		if len(resultRows.Array()) == 0 {
			break
		}

		if resultRows.IsArray() {
			list := make([]models.SysMemberGoods, 0)
			for i := 0; i < len(resultRows.Array()); i++ {
				memberGoods := models.SysMemberGoods{}
				arr := resultRows.Array()[i]
				memberGoods.Category = arr.Get("segment2").Str
				memberGoods.GoodsType = arr.Get("segment4").Str
				memberGoods.GoodsModel = arr.Get("segment5").Str
				memberGoods.GoodsCode = arr.Get("item_code").Str
				memberGoods.GoodsName = arr.Get("item_name").Str
				memberGoods.GoodsSpeci = arr.Get("item_unit").Str
				memberGoods.IsDeleted = "0"
				memberGoods.Status = "1"
				memberGoods.CreatedAt = time.Now()
				memberGoods.UpdatedAt = time.Now()
				list = append(list, memberGoods)
			}
			db, err := e.MakeContext(c).GetOrm()
			if err != nil {
				e.Logger.Error(err)
				e.Error(500, err, err.Error())
				return
			}
			db.Clauses(clause.OnConflict{
				Columns:   []clause.Column{{Name: "goodsCode"}},
				DoUpdates: clause.AssignmentColumns([]string{"category", "goods_type", "goods_model", "goods_name", "goods_speci", "remark"}),
			}).CreateInBatches(list, 200)
		}
		pageNum++
	}

}

// GetPage 获取线下会员商品表列表
// @Summary 获取线下会员商品表列表
// @Description 获取线下会员商品表列表
// @Tags 线下会员商品表
// @Param id query int false "主键Id"
// @Param category query string false "分类"
// @Param goodsType query string false "商品大类"
// @Param goodsModel query string false "商品型号"
// @Param goodsCode query string false "商品编码"
// @Param goodsName query string false "商品名称"
// @Param goodsSpeci query string false "商品规格"
// @Param remark query string false "备注"
// @Param status query string false "业务状态"
// @Param isDeleted query string false "删除状态"
// @Param createTime query time.Time false "创建时间"
// @Param createAccount query string false "创建人"
// @Param createOrg query string false "创建部门"
// @Param updateAccount query string false "修改人"
// @Param updateTime query time.Time false "修改时间"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]models.SysMemberGoods}} "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-member-goods [get]
// @Security Bearer
func (e SysMemberGoods) GetPage(c *gin.Context) {
	req := dto.SysMemberGoodsGetPageReq{}
	s := service.SysMemberGoods{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)
	list := make([]models.SysMemberGoods, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取线下会员商品表 失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Get 获取线下会员商品表
// @Summary 获取线下会员商品表
// @Description 获取线下会员商品表
// @Tags 线下会员商品表
// @Param id path string false "id"
// @Success 200 {object} response.Response{data=models.SysMemberGoods} "{"code": 200, "data": [...]}"
// @Router /api/v1/sys-member-goods/{id} [get]
// @Security Bearer
func (e SysMemberGoods) Get(c *gin.Context) {
	req := dto.SysMemberGoodsGetReq{}
	s := service.SysMemberGoods{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var object models.SysMemberGoods

	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &object)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取线下会员商品表失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.OK(object, "查询成功")
}

// Insert 创建线下会员商品表
// @Summary 创建线下会员商品表
// @Description 创建线下会员商品表
// @Tags 线下会员商品表
// @Accept application/json
// @Product application/json
// @Param data body dto.SysMemberGoodsInsertReq true "data"
// @Success 200 {object} response.Response	"{"code": 200, "message": "添加成功"}"
// @Router /api/v1/sys-member-goods [post]
// @Security Bearer
func (e SysMemberGoods) Insert(c *gin.Context) {
	req := dto.SysMemberGoodsInsertReq{}
	s := service.SysMemberGoods{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c))

	err = s.Insert(&req)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("创建线下会员商品表  失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.OK(req.GetId(), "创建成功")
}

// Update 修改线下会员商品表
// @Summary 修改线下会员商品表
// @Description 修改线下会员商品表
// @Tags 线下会员商品表
// @Accept application/json
// @Product application/json
// @Param data body dto.SysMemberGoodsUpdateReq true "body"
// @Success 200 {object} response.Response	"{"code": 200, "message": "修改成功"}"
// @Router /api/v1/sys-member-goods/{id} [put]
// @Security Bearer
func (e SysMemberGoods) Update(c *gin.Context) {
	req := dto.SysMemberGoodsUpdateReq{}
	s := service.SysMemberGoods{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c))
	p := actions.GetPermissionFromContext(c)

	err = s.Update(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("修改线下会员商品表 失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "修改成功")
}

// Delete 删除线下会员商品表
// @Summary 删除线下会员商品表
// @Description 删除线下会员商品表
// @Tags 线下会员商品表
// @Param ids body []int false "ids"
// @Success 200 {object} response.Response	"{"code": 200, "message": "删除成功"}"
// @Router /api/v1/sys-member-goods [delete]
// @Security Bearer
func (e SysMemberGoods) Delete(c *gin.Context) {
	s := service.SysMemberGoods{}
	req := dto.SysMemberGoodsDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	// req.SetUpdateBy(user.GetUserId(c))
	p := actions.GetPermissionFromContext(c)

	err = s.Remove(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("删除线下会员商品表失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "删除成功")
}
